import EXIF from 'exif-js'

// 压缩用户上传的图片到375宽，减小请求大小，另外处理了exif中的meta信息，让图片不会错误旋转
export let zipImage = async (base64) => {
  let canvas = document.createElement('canvas')
  let ctx = canvas.getContext('2d')
  let image = new Image()
  image.src = base64
  image.style.position = 'fixed'
  image.style.top = '0'
  image.style.left = '0'
  image.style.opacity = '0'
  image.style.pointerEvents = 'none'
  document.body.appendChild(image)
  let result = await new Promise(resolve => {
    image.onload = () => {
      EXIF.getData(image, function () {
        let ratio = image.clientWidth / image.clientHeight
        let width = 375
        let height = width / ratio
        canvas.width = width
        canvas.height = height
        ctx.drawImage(image, 0, 0, width, height)
        // ctx.drawImage(image, 0, 0, width, height)
        resolve(canvas.toDataURL('image/jpeg', 1.0))
      })
    }
  })
  return result
}

// 用在async函数助中用来异步延迟
export const sleep = (time) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, time)
  })
}
